# -*- coding: utf-8 -*-
# Copyright 2004-2010 Joe Wreschnig, Michael Urman, Iñigo Serna,
#     Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation

import os

from quodlibet import config
from quodlibet import const

from quodlibet.parse import Query
from quodlibet.qltk.cbes import StandaloneEditor
from quodlibet.qltk.songlist import SongList

def get_active_filters():
    return set(filter(lambda f: f,
                      config.get("browsers", "global_filters", "").split("\n")))

def global_filter():
    enabled = config.getboolean("browsers", "global_filters_enabled", False)
    filename = os.path.join(const.USERDIR, "lists", "globalfilters.saved")
    active = get_active_filters()
    values = StandaloneEditor.load_values(filename)
    filters = [q for n, q in values if n in active]
    if not (enabled and os.path.exists(filename) and filters): return
    query = "&(%s)" % (", ".join(filters))
    try: return Query(query, star=SongList.star).search
    except Query.error: pass
